<template>
	<div>
		<picker mode="multiSelector" :value="defaultRegionsComponents" range-key="name" @change="handleArea"
			@columnchange="bindPickerChange" :range="items">
			<text>{{ addressString }}</text>
		</picker>
	</div>
</template>

<script>
	import area from "@/common/json/area.json";
	export default {
		props: {
			regionsString: {
				type: String,
				default: '',
			},
			resgionsIndex: {
				type: String,
				default: '',
			},
		},
		data() {
			return {
				defaultRegionsComponents: [0, 0, 0],
				province: [],
				city: [],
				district: [],
				items: [],
				addressString: "请选择地址",
				addressCode: {},
			};
		},
		created() {
			area.forEach((e) => {
				this.province.push({
					name: e.name,
					code: e.code,
					children: e.children,
				});
			});
			this.city = this.province.find(
				(e) => e.name == this.province[0].name
			).children;
			this.district = this.city.find((e) => e.name == this.city[0].name).children;
			this.items = [this.province, this.city, this.district];
		},
		mounted() {
			if (this.regionsString) {
				this.addressString = this.regionsString;
				this.defaultRegionsComponents = this.resgionsIndex.split(",").map(Number);
			}
		},
		methods: {
			handleArea(e) {
				this.addressString = `${this.province[e.detail.value[0]].name}-${
        this.city[e.detail.value[1]].name
      }-${this.district[e.detail.value[2]].name}`;
				this.addressCode = {
					province: this.province[e.detail.value[0]].code,
					city: this.city[e.detail.value[1]].code,
					county: this.district[e.detail.value[2]].code,
				};
				this.$emit(
					"getRegions",
					this.addressCode,
					this.defaultRegionsComponents,
					this.addressString
				);
			},
			bindPickerChange(e) {
				let col = e.detail.column;
				let row = e.detail.value;
				this.defaultRegionsComponents[col] = row;
				switch (e.detail.column) {
					case 0:
						this.city = this.province.find(
							(a) => a.name == this.province[e.detail.value].name
						).children;
						this.district = this.city.find(
							(a) => a.name == this.city[0].name
						).children;
						this.items = [this.province, this.city, this.district];
						break;
					case 1:
						this.district = this.city.find(
							(a) => a.name == this.city[e.detail.value].name
						).children;
						this.items = [this.province, this.city, this.district];
						break;
					default:
						break;
				}
			},
		},
	};
</script>

<style scoped></style>